<script>
import { isNull } from "@/utils/service";
import {
  create,
  getList,
  getOptions as getGroupOptions,
  remove,
  update
} from "@/views/manage/keyWord/component/groupApi";
import { getCategoryOptions } from "@/views/manage/keyWord/api";

export default {
  name: "keyWordGroup",
  props: {
    show: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    showEdit: {
      type: Boolean,
      default: false
    },
    selectRow: {
      type: Array,
      default: r => []
    },
    groupOptions: {
      type: Array,
      default: r => []
    }
  },
  data() {
    return {
      categoryOptions: [],
      dialog: {
        show: false
      },
      updateGroup: {
        selectId: 0
      },
      commit: {
        show: false,
        title: "新增",
        requestLoading: true,
        param: {
          id: undefined,
          name: "",
          categoryName: ""
        },
        rules: {
          name: [
            {
              validator: (rule, value, callback) => {
                let name = value.replace(/\s/g, "");
                if (isNull(name)) {
                  callback(new Error("请输入组名"));
                }
                callback();
              }, trigger: "blur"
            },
          ],
          categoryName: [
            {
              validator: (rule, value, callback) => {
                if (isNull(value)) {
                  callback(new Error("请选择品类名称"));
                }
                callback();
              }, trigger: "change"
            }
          ]
        }
      },
      table: {
        data: [],
        loading: false
      },
      query: {
        name: "",
        categoryName: ""
      }
    };
  },
  methods: {
    dialogOpen() {
      this.getList();
      this.getCategoryOptions()
      this.dialog.show = true;
    },
    updateGroupShow() {
      let _ = this;
      if (_.groupOptions.length === 0) {
        getGroupOptions(_, r => {
          _.groupOptions = r;
        });
      }
    },
    updateGroupReq() {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let _ = this;
      let ids = JSON.stringify(_.selectRow.map(({ id }) => id));
      _.$request.post({
        url: "operationAid/KeyWordUsageRecord/updateGroup",
        params: {
          groupId: _.updateGroup.selectId,
          idsJson: ids
        },
        success: r => {
          _.$message.success("提交成功");
          _.$emit("updateTable");
        },
        finally: r => {
          loading.close();
        }
      });
    },
    getList() {
      let _ = this;
      _.table.loading = true;
      getList(_, _.query, r => {
          _.table.data = r;
        },
        f => {
          _.table.loading = false;
        }
      );
    },
    resetQuery() {
      this.query.name = "";
      this.getList();
    },
    handleAdd() {
      this.commit.param.name = "";
      this.commit.param.id = undefined;
      this.commit.param.categoryName = ""
      this.commit.show = true;
    },
    handleUpdate(row) {
      this.commit.param.name = row.name;
      this.commit.param.id = row.id;
      this.commit.param.categoryName = row.categoryName || "";
      this.commit.show = true;
    },
    handleDelete(ids) {
      let _ = this;
      remove(this, ids, r => {
        _.$message.success("删除成功");
        _.getList();
      });
    },
    commitForm() {
      let _ = this;
      let okFunc = r => {
        console.log("r : " , r);
        _.$message.success("更新成功");
        _.getList();
        _.commit.show = false;
      };
      _.commit.param.name = _.commit.param.name.replace(/\s/g, "");
      this.$refs["commitForm"].validate((valid) => {
        if (valid) {
          if (isNull(_.commit.param.id)) {
            create(_, _.commit.param, okFunc, f => {
            });
          } else {
            update(_, _.commit.param, okFunc, f => {
            });
          }
        } else {
          return false;
        }
      });
    },
    getCategoryOptions(refresh = false) {
      let _ = this;
      /* 强制刷新 categoryOptions 为空*/
      if (refresh || _.categoryOptions.length === 0) {
        getCategoryOptions(this, "categoryOptions", r => {});
      }

    },
  }
};
</script>

<template>
  <div style="display: inline">
    <el-button
      v-show="show"
      :loading="loading"
      size="mini"
      type="primary"
      @click="dialogOpen"
    >
      分组管理
    </el-button>

    <el-popover
      @show="updateGroupShow"
      style="margin-left: 5px"
      placement="bottom"
      width="330"
      trigger="click"
    >
      <el-select
        style="width: 230px;margin-left: 5px;"
        size="mini" v-model="updateGroup.selectId" clearable filterable placeholder="请选择分组">
        <el-option
          v-for="item in groupOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>

      <el-button
        style="margin-left: 10px;"
        size="mini"
        type="success"
        @click="updateGroupReq"
      >
        提交
      </el-button>

      <el-button
        slot="reference"
        v-show="showEdit"
        :loading="loading"
        :disabled="selectRow.length === 0"
        size="mini"
        type="primary"
      >
        编辑选中数据分组
      </el-button>
    </el-popover>


    <!-- 弹出遮罩层 -->
    <el-drawer
      :visible.sync="dialog.show"
      title="分组管理"
      size="80%"
      direction="btt"
    >
      <div style="margin: 10px">
        <div>
          <el-form :model="query" ref="queryForm" size="mini" :inline="true">
            <el-form-item label="名称">
              <el-input style="width: 200px" v-model="query.name" placeholder="请输入组名" clearable></el-input>
            </el-form-item>

            <el-form-item label="品类" prop="categoryName">
              <el-select
                clearable
                v-model="query.categoryName"
                placeholder="请选择品类名称"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button size="small" type="success" @click="handleAdd">新增</el-button>
        </div>

        <div style="margin:10px 0">
          <el-table
            :data="table.data"
            v-loading="table.loading"
            height="60vh"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="categoryName" label="品类" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column label="操作" width="200">
              <template slot-scope="{row}">
                <el-button size="mini" @click="handleUpdate(row)" type="primary">更新</el-button>
                <el-popconfirm
                  style="margin: 0 5px"
                  confirm-button-text="好的"
                  cancel-button-text="点错了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除此分组吗？"
                  @confirm="handleDelete([row.id])"
                >
                  <el-button
                    slot="reference"
                    size="mini"
                    type="danger">
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-drawer>

    <!-- 新增 -->
    <el-dialog
      :title=commit.title
      :visible.sync="commit.show"
      :close-on-click-modal="false"
      width="40%"
    >
      <el-form
        :model="commit.param"
        ref="commitForm"
        :rules="commit.rules"
        size="mini"
        label-width="80px"
      >
        <el-form-item label="分组名称" prop="name">
          <el-input
            v-model="commit.param.name"
            @input="res => {commit.param.name = res.replace(/\s/g, '')}"
            placeholder="请输入分组名"
            maxlength="30"
            show-word-limit
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="品类名称" prop="categoryName">
          <el-select
            clearable
            v-model="commit.param.categoryName"
            placeholder="请选择品类名称"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
            <el-button @click="commit.show = false">取 消</el-button>
            <el-button type="primary" @click="commitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>